//
//  JSAddressController.m
//  jshop
//
//  Created by 张艳江 on 2019/5/18.
//  Copyright © 2019 张艳江. All rights reserved.
//

#import "SCAddressController.h"
#import "SCAddressListCell.h"
#import "SCEditAddressController.h"

@interface SCAddressController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) NSMutableArray *addressArray;

@end

@implementation SCAddressController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"地址管理";
    
    self.tableView.backgroundColor = BGColor;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.estimatedRowHeight = 122;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerNib:[UINib nibWithNibName:@"SCAddressListCell" bundle:nil] forCellReuseIdentifier:@"SCAddressListCellID"];
    
    //请求地址管理数据
    [SVProgressHUD showWithStatus:@"加载中..."];
    [self requestAddressData];
}
#pragma mark - tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.addressArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SCAddressListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SCAddressListCellID"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.addressArray[indexPath.row];
    [cell.deleteBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [cell.editBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [cell.setDefaultBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isChoose == YES) {
        if (self.chooseAddress) {
            self.chooseAddress(self.addressArray[indexPath.row]);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}
#pragma mark - 删除编辑
- (void)clickBtn:(UIButton *)sender{
    
    UITableViewCell *cell = (UITableViewCell *)[[sender superview]superview];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    SCModel *model = self.addressArray[indexPath.row];
    if (sender.tag == 0) {//编辑
        SCEditAddressController *vc = [[SCEditAddressController alloc]init];
        vc.title = @"编辑地址";
        vc.model = model;
        WeakSelf;
        vc.refreshData = ^{
            [weakSelf requestAddressData];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }else if (sender.tag == 1){//删除
        
        [MyTool alertTitle:@"您确定要删除当前地址吗?" mesasge:nil preferredStyle:UIAlertControllerStyleAlert confirmHandler:^(UIAlertAction * _Nonnull action) {
            
            NSDictionary *dict = @{@"adress_id":model.adress_id,
                                   @"token":Token};
            NSString *url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GiftAppOrder&a=App_address_del"];
            [SVProgressHUD showWithStatus:@"删除中..."];
            [[NetworkRequestTool sharedNetworkTool] POST:url parameters:dict finished:^(id result, NSString *error) {
                [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                //NSLog(@"----%@",result);
                [self.addressArray removeObjectAtIndex:indexPath.row];
                [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }];
        } cancleHandler:nil viewController:self];
    }else{
        
        NSDictionary *dict = @{@"token":Token,
                               @"adress_id":model.adress_id};
        NSString *url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GiftAppOrder&a=App_address_default"];
        [SVProgressHUD showWithStatus:@"修改中..."];
        [[NetworkRequestTool sharedNetworkTool] POST:url parameters:dict finished:^(id result, NSString *error) {
            [SVProgressHUD showSuccessWithStatus:@"修改成功"];
            for (SCModel *addressModel in self.addressArray) {
                if ([addressModel.adress_id isEqualToString:model.adress_id]) {
                    addressModel.is_def = @"1";
                }else{
                    addressModel.is_def = @"0";
                }
            }
            [self.tableView reloadData];
        }];
    }
}

#pragma mark - 请求数据
- (void)requestAddressData{
    
    NSDictionary *dict = @{@"token":Token};
    NSString *url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GiftAppOrder&a=App_address_list"];
    [[NetworkRequestTool sharedNetworkTool] POST:url parameters:dict finished:^(id result, NSString *error) {
        [SVProgressHUD dismiss];
        //NSLog(@"地址列表：%@",result);
        NSArray *tempArray = [SCModel mj_objectArrayWithKeyValuesArray:result[@"data"]];
        self.addressArray = [NSMutableArray array];
        [self.addressArray addObjectsFromArray:tempArray];
        [self.tableView reloadData];
    }];
}

//添加地址
- (IBAction)clickAddAdressBtn:(UIButton *)sender {
    
    SCEditAddressController *vc = [[SCEditAddressController alloc]init];
    vc.title = @"添加地址";
    WeakSelf;
    vc.refreshData = ^{
        [weakSelf requestAddressData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}


@end
